<template>
  <div class="permission-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAdd">新增权限</el-button>
        </div>
      </template>
      
      <!-- 权限树 -->
      <el-table
        :data="permissionTree"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="权限名称" width="200" />
        <el-table-column prop="code" label="权限编码" width="200" />
        <el-table-column prop="url" label="URL" width="200" />
        <el-table-column prop="method" label="HTTP方法" width="120">
          <template #default="scope">
            <el-tag :type="getMethodTagType(scope.row.method)">
              {{ scope.row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="显示"
              inactive-text="隐藏"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 权限编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="currentPermission" label-width="100px">
        <el-form-item label="父级权限">
          <el-tree-select
            v-model="currentPermission.parentId"
            :data="permissionTreeForSelect"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            node-key="id"
            placeholder="请选择父级权限"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="currentPermission.name" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="currentPermission.code" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="currentPermission.url" />
        </el-form-item>
        <el-form-item label="HTTP方法" prop="method">
          <el-select v-model="currentPermission.method" placeholder="请选择HTTP方法">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="currentPermission.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="currentPermission.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentPermission.status"
            :active-value="1"
            :inactive-value="0"
            active-text="显示"
            inactive-text="隐藏"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermission">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAllPermissionTree, 
  addPermission, 
  updatePermission, 
  deletePermission,
  togglePermissionStatus
} from '@/api/permission'

// 权限树数据
const permissionTree = ref([])
const permissionTreeForSelect = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 当前编辑的权限
const currentPermission = reactive({
  id: 0,
  name: '',
  code: '',
  url: '',
  method: 'GET',
  description: '',
  parentId: 0,
  sortOrder: 0,
  status: 1
})

// 获取HTTP方法标签类型
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': '',
    'POST': 'success',
    'PUT': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || ''
}

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const response = await getAllPermissionTree()
    if (response.code === 200) {
      permissionTree.value = response.data
      // 构造用于选择的权限树（排除当前编辑的权限）
      permissionTreeForSelect.value = buildPermissionTreeForSelect(response.data)
    } else {
      ElMessage.error(response.message || '获取权限树失败')
    }
  } catch (err) {
    ElMessage.error('获取权限树失败')
  } finally {
    loading.value = false
  }
}

// 构造用于选择的权限树
const buildPermissionTreeForSelect = (data) => {
  // 添加"顶级权限"选项
  const result = [{
    id: 0,
    name: '顶级权限',
    children: []
  }]
  
  // 递归处理子节点
  const processChildren = (nodes, parent) => {
    nodes.forEach(node => {
      const newNode = {
        id: node.id,
        name: node.name,
        children: []
      }
      
      if (node.children && node.children.length > 0) {
        processChildren(node.children, newNode.children)
      }
      
      parent.push(newNode)
    })
  }
  
  processChildren(data, result[0].children)
  return result
}

// 处理新增权限
const handleAdd = () => {
  dialogTitle.value = '新增权限'
  isEdit.value = false
  // 重置表单
  Object.assign(currentPermission, {
    id: 0,
    name: '',
    code: '',
    url: '',
    method: 'GET',
    description: '',
    parentId: 0,
    sortOrder: 0,
    status: 1
  })
  dialogVisible.value = true
}

// 处理编辑权限
const handleEdit = (permission) => {
  dialogTitle.value = '编辑权限'
  isEdit.value = true
  // 填充表单数据
  Object.assign(currentPermission, permission)
  dialogVisible.value = true
}

// 保存权限
const savePermission = async () => {
  try {
    let response
    if (isEdit.value) {
      response = await updatePermission(currentPermission)
    } else {
      response = await addPermission(currentPermission)
    }
    
    if (response.code === 200) {
      ElMessage.success(`${isEdit.value ? '编辑' : '新增'}权限成功`)
      dialogVisible.value = false
      fetchPermissionTree()
    } else {
      ElMessage.error(response.message || `${isEdit.value ? '编辑' : '新增'}权限失败`)
    }
  } catch (err) {
    ElMessage.error(`${isEdit.value ? '编辑' : '新增'}权限失败`)
  }
}

// 处理删除权限
const handleDelete = (permission) => {
  ElMessageBox.confirm(`确定要删除权限"${permission.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deletePermission(permission.id)
      if (response.code === 200) {
        ElMessage.success('删除权限成功')
        fetchPermissionTree()
      } else {
        ElMessage.error(response.message || '删除权限失败')
      }
    } catch (err) {
      ElMessage.error('删除权限失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理权限状态切换
const handleStatusChange = async (permission) => {
  try {
    const response = await togglePermissionStatus(permission.id, permission.status)
    if (response.code === 200) {
      ElMessage.success('权限状态更新成功')
      // 更新本地数据
      const updatePermissionStatus = (permissions) => {
        permissions.forEach(p => {
          if (p.id === permission.id) {
            p.status = permission.status
          }
          if (p.children && p.children.length > 0) {
            updatePermissionStatus(p.children)
          }
        })
      }
      updatePermissionStatus(permissionTree.value)
    } else {
      // 恢复状态
      permission.status = permission.status === 1 ? 0 : 1
      ElMessage.error(response.message || '权限状态更新失败')
    }
  } catch (err) {
    // 恢复状态
    permission.status = permission.status === 1 ? 0 : 1
    ElMessage.error('权限状态更新失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPermissionTree()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>